<?php
namespace App\Http\Controllers\Admin;

use App\Models\Cms_District;
use App\Models\Cms_Params;
use App\Services\DistrictService;
use App\Third\Qiniu\Token;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Qiniu\Storage\UploadManager;

class CommonController extends Controller
{
    /*
     * 获取省、市、区树形结构
     *
     * Author:kayson
     * */
    public function districtTree()
    {
        $arr = Cms_District::get()->toArray();
        $result = $this->subTree($arr);
        return $this->responseSuccess($result);
    }

    /*
     * 获取配置参数
     *
     * Author:kayson
     * */
    public function getParams()
    {
        $result = Cms_Params::get();
        $restructured = [];
        foreach ($result as $value){
            $arr = [];
            $itemvalue = json_decode($value['itemvalue'],true);
            foreach ($itemvalue as $key => $val){
                $arr[] = [
                    'label' => $val,
                    'value' => $key
                ];
            }
            $restructured[$value['itemcode']] = $arr;
        }
        return $this->responseSuccess($restructured);
    }

    /*
     * 获取省、市、区列表
     *
     * Author:kayson
     * */
    public function district_list(DistrictService $districtService , Request $request)
    {
        $params = $request->input();

        $result = $districtService->getDistrict($params);

        return $this->success(200,$result['data']);
    }

    public function upload(Request $request){
        $file = $request->file('file');//获取文件
        if ($file) {

            //获取文件的原文件名 包括扩展名
            $yuanname = $file->getClientOriginalName();

            //获取文件的扩展名
            $kuoname = $file->getClientOriginalExtension();

            //获取文件的类型
            $type = $file->getClientMimeType();

            //获取文件的绝对路径，但是获取到的在本地不能打开
            $path = $file->getRealPath();

            //要保存的文件名 时间 扩展名
            $filename = 'img' . '/' . date('Y-m-d') . '/' . uniqid() . '.' . $kuoname;
            //保存文件   配置文件存放文件的名字 ，文件名，路径
            $bool = Storage::disk('uploadimg')->put($filename, file_get_contents($path));
            $filePath = Storage::url($filename);
            return $this->success(200, $filePath);
        }
}

    public function fileAdd(Request $request)
    {
        $file = $request->file('file');
        $type = $request->input('type') ?? 'default';
        $uptoken = Token::getToken();
        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        //图片文件的生成
        $filePath = $file->getPathname();

        // 上传到七牛后保存的文件名
        $fileName = md5($file->getClientOriginalName().time().rand()).'.'.$file->getClientOriginalExtension();
        list($ret, $error) = $uploadMgr->putFile($uptoken, $type.'/image_'.$fileName, $filePath);

        $path = config('filesystems.disks.qiniu')['domain'] . $ret['key'];
        if ($error !== null) {
            return $this->fail(1003, $_FILES["file"]["error"]);
        } else {
            return $this->success(200, $path);
        }
    }

    public function file_del(Request $request)
    {
        $headimg = $request->input('headimg');
        //域名长度
        $len = strlen(config('filesystems.disks')['qiniu']['domain']);
        //要删除七牛云图片路径
        $key = substr($headimg,$len);
        $auth = new Auth(config('filesystems.disks')['qiniu']['access_key'], config('filesystems.disks')['qiniu']['secret_key']);
        $config = new Config();
        $bucketManager = new BucketManager($auth, $config);
        $err = $bucketManager->delete(config('filesystems.disks')['qiniu']['bucket'], $key);
        if (empty($err[1])) {
            return $this->success(200,[]);
        }else{
            return $this->fail(1005);
        }
    }

    public function getImgData($img_url)
    {
        $ch = curl_init($img_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        //读取图片数据
        $rawData = curl_exec($ch);
        curl_close($ch);

        return $rawData;
    }

    //网络图片上传图片到七牛云
    public function image_add($img_url)
    {
        $imageData = $this->getImgData($img_url);
        $uptoken = Token::getToken();;

        // 构建 UploadManager 对象
        $uploadMgr = new UploadManager();
        $key   = 'xiumi/xiumi_'.time().rand().'.png';//存储图片名称
        $mime  = 'image/jpeg';

        list($rest, $err) = $uploadMgr->put($uptoken, $key, $imageData, null, $mime);
        if ($err) {
            return $this->fail(1003, $err);
        } else {
            $uploadurl = config('filesystems.disks.qiniu')['domain'].$rest['key'];//七牛存储图片地址
            return $this->success(200, $uploadurl);
        }
    }

    /*
         * 百度编辑器
         *
         * Author:kayson
         * */


    public function ueditor_config(Request $request)
    {
        $action = $request->input('action');
        $callback = $request->input('callback');
        $config = [
            // 上传图片配置项
            "imageActionName" => "image",
            "imageFieldName" => "file",
            "imageMaxSize" => 1024 * 1024 * 10,
            "imageAllowFiles" => ['.jpg', '.png', '.jpeg'],
            "imageCompressEnable" => true,
            "imageCompressBorder" => 5000,
            "imageInsertAlign" => "none",
            "imageUrlPrefix" => "",

            // 抓取远程配置
            "catcherActionName" => "catchimage",
            "catcherFieldName" => "source",
            "catcherUrlPrefix" => "",
            "catcherMaxSize" => 1024 * 1024 * 10,
            "catcherAllowFiles" => [".png", ".jpg", ".jpeg", ".gif", ".bmp"],


            // 上传视频配置
            "videoActionName" => "video",
            "videoFieldName" => "file",
            "videoUrlPrefix" => "",
            "videoMaxSize" => 1024 * 1024 * 100,
            "videoAllowFiles" => ['.mp4'],

            // 上传文件配置
            "fileActionName" => "file",
            "fileFieldName" => "file",
            "fileUrlPrefix" => "",
            "fileMaxSize" => 1024 * 1024 * 100,
            "fileAllowFiles" => ['.zip', '.pdf', '.doc'],

            // 列出图片
            "imageManagerActionName" => "listImage",
            "imageManagerListSize" => 20,
            "imageManagerUrlPrefix" => "",
            "imageManagerInsertAlign" => "none",
            "imageManagerAllowFiles" => ['.jpg', '.png', '.jpeg'],

            // 列出指定目录下的文件
            "fileManagerActionName" => "listFile",
            "fileManagerUrlPrefix" => "",
            "fileManagerListSize" => 20,
            "fileManagerAllowFiles" => ['.zip', '.pdf', '.doc'],

            // 公式渲染
            "formulaConfig" => [
                "imageUrlTemplate"=>"http://latex.codecogs.com/svg.image?{}",
            ]

        ];

        switch ($action) {

            case 'image':
                $common = new CommonController();
                $result = $common->file_add($request);
                $name = isset($request->input['name']) ? $request->input['name'] : '';
                return response()->json([
                    'state' => 'SUCCESS',
                    'url' => $result->getData()->data . '?name=' . urlencode($name),
                ]);

            case 'video':
                $common = new CommonController();
                $result = $common->file_add($request);

                return response()->json([
                    'state' => 'SUCCESS',
                    'url' => $result->getData()->data,
                ]);

            case 'file':
                $common = new CommonController();
                $result = $common->file_add($request);

                return response()->json([
                    'state' => 'SUCCESS',
                    'url' => $result->getData(),
                ]);
            case 'catchimage':
                $common = new CommonController();
                $source = $request->input('source');
                $arr = [];
                foreach ($source as $s){
                    $url = $common->image_add($s);

                    array_push($arr,['state' => 'SUCCESS','source' => $s, 'url' => $url->getData()->data,]);
                }

                return response()->json([
                    'state' => 'SUCCESS',
                    'list' => $arr,
                ])->setCallback($callback);
            default:
                return response()->json($config)->setCallback($callback);
        }

    }
}
